Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [2]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [3]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.
In [4]:
human_files
Out[4]:
array(['lfw\\Muhammad_Ali\\Muhammad_Ali_0001.jpg',
       'lfw\\Yoko_Ono\\Yoko_Ono_0001.jpg',
       'lfw\\Svetlana_Koroleva\\Svetlana_Koroleva_0002.jpg', ...,
       'lfw\\Mahmoud_Abbas\\Mahmoud_Abbas_0028.jpg',
       'lfw\\Ernie_Fletcher\\Ernie_Fletcher_0002.jpg',
       'lfw\\John_Ashcroft\\John_Ashcroft_0028.jpg'], 
      dtype='<U84')

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [5]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1
In [6]:
plt.imshow(img)
plt.show()
In [7]:
img.shape
Out[7]:
(250, 250, 3)
In [12]:
img_dog = cv2.imread(train_files[70])
img_dog.shape
Out[12]:
(427, 640, 3)

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [13]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: 99% of the images in human_files_short were correctly detected to have a human face, while 11% of the images in dog_files_short were incorrectly identified to have a human face.

In [14]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
def percentage_face_detected(img_list):
    percent = 100 * sum([1.0 for img_path in img_list if face_detector(img_path)])/len(img_list)
    print("Percentage of images with detected human face: {}%".format(percent))
    
print("Testing human_files_short- ", end="\t")
percentage_face_detected(human_files_short)
print("Testing dog_files_short- ", end="\t")
percentage_face_detected(dog_files_short)
Testing human_files_short- 	Percentage of images with detected human face: 99.0%
Testing dog_files_short- 	Percentage of images with detected human face: 11.0%

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: I think it is reasonable to reject human images without a view of a face if the users are expecting the app to show them the dog breed their faces most closely resembles. We can possibly drop this requirement for more entertainment value to match poses or clothing to match the dog breeds as predicted by the CNN models, as it is not certain the CNN models have trained to focus only on the dog faces. The Haar cascades in this case have a one in ten error rate of detecting dogs as human, though the algorithm fares better on the human images, with only 1% false negative rate. If we expect users to only input dog or human images, we can use the more accurate CNN based dog detector to determine if the image contains a dog, otherwise use the Haar cascade to determine if the image that doesn't have a dog contains a human face. We can also consider using the built in detector in OpenCV based on the ideas described in the Histograms of Oriented Gradients for Human Detection paper that recognises human figures in upright poses. However images accepted to contain humans with this method might yield matches in the dog breed recogniser that are not based on inputs from facial features, since the images might not show faces clearly, and the inputs might be the human body contours, clothing patterns or elements from the background, and different photos of the same user in different clothing might result in different matching dog breeds.

    # https://github.com/opencv/opencv/blob/master/samples/python/peopledetect.py
    hog = cv.HOGDescriptor()
    hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
    found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [15]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.
lbp_face_cascade = cv2.CascadeClassifier('lbpcascades/lbpcascade_frontalface_improved.xml')

def face_detector_2(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = lbp_face_cascade.detectMultiScale(gray)
    return len(faces) > 0

def percentage_face_detected_2(img_list):
    percent = 100 * sum([1.0 for img_path in img_list if face_detector_2(img_path)])/len(img_list)
    print("Percentage of images with detected human face: {}%".format(percent))
    
print("Testing human_files_short- ", end="\t")
percentage_face_detected_2(human_files_short)
print("Testing dog_files_short- ", end="\t")
percentage_face_detected_2(dog_files_short)
Testing human_files_short- 	Percentage of images with detected human face: 92.0%
Testing dog_files_short- 	Percentage of images with detected human face: 1.0%

Tested with the Local Binary Pattern cascade classifier trained on frontal faces in OpenCV. This gave a lower accuracy of 92% with human images, but also smaller false positive error rate of 1% with the dog images. However, for our use case, this would lead to a higher percentage of rejected images with humans in them, which makes for a less enjoyable app.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [16]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
In [17]:
dir(ResNet50_model)
Out[17]:
['__call__',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_add_inbound_node',
 '_feed_input_names',
 '_feed_input_shapes',
 '_feed_inputs',
 '_fit_loop',
 '_get_node_attribute_at_index',
 '_make_predict_function',
 '_make_test_function',
 '_make_train_function',
 '_output_mask_cache',
 '_output_shape_cache',
 '_output_tensor_cache',
 '_predict_loop',
 '_standardize_user_data',
 '_test_loop',
 '_updated_config',
 'add_loss',
 'add_update',
 'add_weight',
 'assert_input_compatibility',
 'build',
 'built',
 'call',
 'compile',
 'compute_mask',
 'compute_output_shape',
 'constraints',
 'container_nodes',
 'count_params',
 'evaluate',
 'evaluate_generator',
 'fit',
 'fit_generator',
 'from_config',
 'get_config',
 'get_input_at',
 'get_input_mask_at',
 'get_input_shape_at',
 'get_layer',
 'get_losses_for',
 'get_output_at',
 'get_output_mask_at',
 'get_output_shape_at',
 'get_updates_for',
 'get_weights',
 'inbound_nodes',
 'input',
 'input_layers',
 'input_layers_node_indices',
 'input_layers_tensor_indices',
 'input_mask',
 'input_names',
 'input_shape',
 'input_spec',
 'inputs',
 'internal_input_shapes',
 'internal_output_shapes',
 'layers',
 'layers_by_depth',
 'load_weights',
 'losses',
 'name',
 'nodes_by_depth',
 'non_trainable_weights',
 'outbound_nodes',
 'output',
 'output_layers',
 'output_layers_node_indices',
 'output_layers_tensor_indices',
 'output_mask',
 'output_names',
 'output_shape',
 'outputs',
 'predict',
 'predict_generator',
 'predict_on_batch',
 'reset_states',
 'run_internal_graph',
 'save',
 'save_weights',
 'set_weights',
 'state_updates',
 'stateful',
 'summary',
 'supports_masking',
 'test_on_batch',
 'to_json',
 'to_yaml',
 'train_on_batch',
 'trainable',
 'trainable_weights',
 'updates',
 'uses_learning_phase',
 'weights']
In [18]:
ResNet50_model.summary()
____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
input_1 (InputLayer)             (None, 224, 224, 3)   0                                            
____________________________________________________________________________________________________
zero_padding2d_1 (ZeroPadding2D) (None, 230, 230, 3)   0                                            
____________________________________________________________________________________________________
conv1 (Conv2D)                   (None, 112, 112, 64)  9472                                         
____________________________________________________________________________________________________
bn_conv1 (BatchNormalization)    (None, 112, 112, 64)  256                                          
____________________________________________________________________________________________________
activation_1 (Activation)        (None, 112, 112, 64)  0                                            
____________________________________________________________________________________________________
max_pooling2d_1 (MaxPooling2D)   (None, 55, 55, 64)    0                                            
____________________________________________________________________________________________________
res2a_branch2a (Conv2D)          (None, 55, 55, 64)    4160                                         
____________________________________________________________________________________________________
bn2a_branch2a (BatchNormalizatio (None, 55, 55, 64)    256                                          
____________________________________________________________________________________________________
activation_2 (Activation)        (None, 55, 55, 64)    0                                            
____________________________________________________________________________________________________
res2a_branch2b (Conv2D)          (None, 55, 55, 64)    36928                                        
____________________________________________________________________________________________________
bn2a_branch2b (BatchNormalizatio (None, 55, 55, 64)    256                                          
____________________________________________________________________________________________________
activation_3 (Activation)        (None, 55, 55, 64)    0                                            
____________________________________________________________________________________________________
res2a_branch2c (Conv2D)          (None, 55, 55, 256)   16640                                        
____________________________________________________________________________________________________
res2a_branch1 (Conv2D)           (None, 55, 55, 256)   16640                                        
____________________________________________________________________________________________________
bn2a_branch2c (BatchNormalizatio (None, 55, 55, 256)   1024                                         
____________________________________________________________________________________________________
bn2a_branch1 (BatchNormalization (None, 55, 55, 256)   1024                                         
____________________________________________________________________________________________________
add_1 (Add)                      (None, 55, 55, 256)   0                                            
____________________________________________________________________________________________________
activation_4 (Activation)        (None, 55, 55, 256)   0                                            
____________________________________________________________________________________________________
res2b_branch2a (Conv2D)          (None, 55, 55, 64)    16448                                        
____________________________________________________________________________________________________
bn2b_branch2a (BatchNormalizatio (None, 55, 55, 64)    256                                          
____________________________________________________________________________________________________
activation_5 (Activation)        (None, 55, 55, 64)    0                                            
____________________________________________________________________________________________________
res2b_branch2b (Conv2D)          (None, 55, 55, 64)    36928                                        
____________________________________________________________________________________________________
bn2b_branch2b (BatchNormalizatio (None, 55, 55, 64)    256                                          
____________________________________________________________________________________________________
activation_6 (Activation)        (None, 55, 55, 64)    0                                            
____________________________________________________________________________________________________
res2b_branch2c (Conv2D)          (None, 55, 55, 256)   16640                                        
____________________________________________________________________________________________________
bn2b_branch2c (BatchNormalizatio (None, 55, 55, 256)   1024                                         
____________________________________________________________________________________________________
add_2 (Add)                      (None, 55, 55, 256)   0                                            
____________________________________________________________________________________________________
activation_7 (Activation)        (None, 55, 55, 256)   0                                            
____________________________________________________________________________________________________
res2c_branch2a (Conv2D)          (None, 55, 55, 64)    16448                                        
____________________________________________________________________________________________________
bn2c_branch2a (BatchNormalizatio (None, 55, 55, 64)    256                                          
____________________________________________________________________________________________________
activation_8 (Activation)        (None, 55, 55, 64)    0                                            
____________________________________________________________________________________________________
res2c_branch2b (Conv2D)          (None, 55, 55, 64)    36928                                        
____________________________________________________________________________________________________
bn2c_branch2b (BatchNormalizatio (None, 55, 55, 64)    256                                          
____________________________________________________________________________________________________
activation_9 (Activation)        (None, 55, 55, 64)    0                                            
____________________________________________________________________________________________________
res2c_branch2c (Conv2D)          (None, 55, 55, 256)   16640                                        
____________________________________________________________________________________________________
bn2c_branch2c (BatchNormalizatio (None, 55, 55, 256)   1024                                         
____________________________________________________________________________________________________
add_3 (Add)                      (None, 55, 55, 256)   0                                            
____________________________________________________________________________________________________
activation_10 (Activation)       (None, 55, 55, 256)   0                                            
____________________________________________________________________________________________________
res3a_branch2a (Conv2D)          (None, 28, 28, 128)   32896                                        
____________________________________________________________________________________________________
bn3a_branch2a (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_11 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3a_branch2b (Conv2D)          (None, 28, 28, 128)   147584                                       
____________________________________________________________________________________________________
bn3a_branch2b (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_12 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3a_branch2c (Conv2D)          (None, 28, 28, 512)   66048                                        
____________________________________________________________________________________________________
res3a_branch1 (Conv2D)           (None, 28, 28, 512)   131584                                       
____________________________________________________________________________________________________
bn3a_branch2c (BatchNormalizatio (None, 28, 28, 512)   2048                                         
____________________________________________________________________________________________________
bn3a_branch1 (BatchNormalization (None, 28, 28, 512)   2048                                         
____________________________________________________________________________________________________
add_4 (Add)                      (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
activation_13 (Activation)       (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
res3b_branch2a (Conv2D)          (None, 28, 28, 128)   65664                                        
____________________________________________________________________________________________________
bn3b_branch2a (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_14 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3b_branch2b (Conv2D)          (None, 28, 28, 128)   147584                                       
____________________________________________________________________________________________________
bn3b_branch2b (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_15 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3b_branch2c (Conv2D)          (None, 28, 28, 512)   66048                                        
____________________________________________________________________________________________________
bn3b_branch2c (BatchNormalizatio (None, 28, 28, 512)   2048                                         
____________________________________________________________________________________________________
add_5 (Add)                      (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
activation_16 (Activation)       (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
res3c_branch2a (Conv2D)          (None, 28, 28, 128)   65664                                        
____________________________________________________________________________________________________
bn3c_branch2a (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_17 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3c_branch2b (Conv2D)          (None, 28, 28, 128)   147584                                       
____________________________________________________________________________________________________
bn3c_branch2b (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_18 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3c_branch2c (Conv2D)          (None, 28, 28, 512)   66048                                        
____________________________________________________________________________________________________
bn3c_branch2c (BatchNormalizatio (None, 28, 28, 512)   2048                                         
____________________________________________________________________________________________________
add_6 (Add)                      (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
activation_19 (Activation)       (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
res3d_branch2a (Conv2D)          (None, 28, 28, 128)   65664                                        
____________________________________________________________________________________________________
bn3d_branch2a (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_20 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3d_branch2b (Conv2D)          (None, 28, 28, 128)   147584                                       
____________________________________________________________________________________________________
bn3d_branch2b (BatchNormalizatio (None, 28, 28, 128)   512                                          
____________________________________________________________________________________________________
activation_21 (Activation)       (None, 28, 28, 128)   0                                            
____________________________________________________________________________________________________
res3d_branch2c (Conv2D)          (None, 28, 28, 512)   66048                                        
____________________________________________________________________________________________________
bn3d_branch2c (BatchNormalizatio (None, 28, 28, 512)   2048                                         
____________________________________________________________________________________________________
add_7 (Add)                      (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
activation_22 (Activation)       (None, 28, 28, 512)   0                                            
____________________________________________________________________________________________________
res4a_branch2a (Conv2D)          (None, 14, 14, 256)   131328                                       
____________________________________________________________________________________________________
bn4a_branch2a (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_23 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4a_branch2b (Conv2D)          (None, 14, 14, 256)   590080                                       
____________________________________________________________________________________________________
bn4a_branch2b (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_24 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4a_branch2c (Conv2D)          (None, 14, 14, 1024)  263168                                       
____________________________________________________________________________________________________
res4a_branch1 (Conv2D)           (None, 14, 14, 1024)  525312                                       
____________________________________________________________________________________________________
bn4a_branch2c (BatchNormalizatio (None, 14, 14, 1024)  4096                                         
____________________________________________________________________________________________________
bn4a_branch1 (BatchNormalization (None, 14, 14, 1024)  4096                                         
____________________________________________________________________________________________________
add_8 (Add)                      (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
activation_25 (Activation)       (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
res4b_branch2a (Conv2D)          (None, 14, 14, 256)   262400                                       
____________________________________________________________________________________________________
bn4b_branch2a (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_26 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4b_branch2b (Conv2D)          (None, 14, 14, 256)   590080                                       
____________________________________________________________________________________________________
bn4b_branch2b (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_27 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4b_branch2c (Conv2D)          (None, 14, 14, 1024)  263168                                       
____________________________________________________________________________________________________
bn4b_branch2c (BatchNormalizatio (None, 14, 14, 1024)  4096                                         
____________________________________________________________________________________________________
add_9 (Add)                      (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
activation_28 (Activation)       (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
res4c_branch2a (Conv2D)          (None, 14, 14, 256)   262400                                       
____________________________________________________________________________________________________
bn4c_branch2a (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_29 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4c_branch2b (Conv2D)          (None, 14, 14, 256)   590080                                       
____________________________________________________________________________________________________
bn4c_branch2b (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_30 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4c_branch2c (Conv2D)          (None, 14, 14, 1024)  263168                                       
____________________________________________________________________________________________________
bn4c_branch2c (BatchNormalizatio (None, 14, 14, 1024)  4096                                         
____________________________________________________________________________________________________
add_10 (Add)                     (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
activation_31 (Activation)       (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
res4d_branch2a (Conv2D)          (None, 14, 14, 256)   262400                                       
____________________________________________________________________________________________________
bn4d_branch2a (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_32 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4d_branch2b (Conv2D)          (None, 14, 14, 256)   590080                                       
____________________________________________________________________________________________________
bn4d_branch2b (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_33 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4d_branch2c (Conv2D)          (None, 14, 14, 1024)  263168                                       
____________________________________________________________________________________________________
bn4d_branch2c (BatchNormalizatio (None, 14, 14, 1024)  4096                                         
____________________________________________________________________________________________________
add_11 (Add)                     (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
activation_34 (Activation)       (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
res4e_branch2a (Conv2D)          (None, 14, 14, 256)   262400                                       
____________________________________________________________________________________________________
bn4e_branch2a (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_35 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4e_branch2b (Conv2D)          (None, 14, 14, 256)   590080                                       
____________________________________________________________________________________________________
bn4e_branch2b (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_36 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4e_branch2c (Conv2D)          (None, 14, 14, 1024)  263168                                       
____________________________________________________________________________________________________
bn4e_branch2c (BatchNormalizatio (None, 14, 14, 1024)  4096                                         
____________________________________________________________________________________________________
add_12 (Add)                     (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
activation_37 (Activation)       (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
res4f_branch2a (Conv2D)          (None, 14, 14, 256)   262400                                       
____________________________________________________________________________________________________
bn4f_branch2a (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_38 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4f_branch2b (Conv2D)          (None, 14, 14, 256)   590080                                       
____________________________________________________________________________________________________
bn4f_branch2b (BatchNormalizatio (None, 14, 14, 256)   1024                                         
____________________________________________________________________________________________________
activation_39 (Activation)       (None, 14, 14, 256)   0                                            
____________________________________________________________________________________________________
res4f_branch2c (Conv2D)          (None, 14, 14, 1024)  263168                                       
____________________________________________________________________________________________________
bn4f_branch2c (BatchNormalizatio (None, 14, 14, 1024)  4096                                         
____________________________________________________________________________________________________
add_13 (Add)                     (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
activation_40 (Activation)       (None, 14, 14, 1024)  0                                            
____________________________________________________________________________________________________
res5a_branch2a (Conv2D)          (None, 7, 7, 512)     524800                                       
____________________________________________________________________________________________________
bn5a_branch2a (BatchNormalizatio (None, 7, 7, 512)     2048                                         
____________________________________________________________________________________________________
activation_41 (Activation)       (None, 7, 7, 512)     0                                            
____________________________________________________________________________________________________
res5a_branch2b (Conv2D)          (None, 7, 7, 512)     2359808                                      
____________________________________________________________________________________________________
bn5a_branch2b (BatchNormalizatio (None, 7, 7, 512)     2048                                         
____________________________________________________________________________________________________
activation_42 (Activation)       (None, 7, 7, 512)     0                                            
____________________________________________________________________________________________________
res5a_branch2c (Conv2D)          (None, 7, 7, 2048)    1050624                                      
____________________________________________________________________________________________________
res5a_branch1 (Conv2D)           (None, 7, 7, 2048)    2099200                                      
____________________________________________________________________________________________________
bn5a_branch2c (BatchNormalizatio (None, 7, 7, 2048)    8192                                         
____________________________________________________________________________________________________
bn5a_branch1 (BatchNormalization (None, 7, 7, 2048)    8192                                         
____________________________________________________________________________________________________
add_14 (Add)                     (None, 7, 7, 2048)    0                                            
____________________________________________________________________________________________________
activation_43 (Activation)       (None, 7, 7, 2048)    0                                            
____________________________________________________________________________________________________
res5b_branch2a (Conv2D)          (None, 7, 7, 512)     1049088                                      
____________________________________________________________________________________________________
bn5b_branch2a (BatchNormalizatio (None, 7, 7, 512)     2048                                         
____________________________________________________________________________________________________
activation_44 (Activation)       (None, 7, 7, 512)     0                                            
____________________________________________________________________________________________________
res5b_branch2b (Conv2D)          (None, 7, 7, 512)     2359808                                      
____________________________________________________________________________________________________
bn5b_branch2b (BatchNormalizatio (None, 7, 7, 512)     2048                                         
____________________________________________________________________________________________________
activation_45 (Activation)       (None, 7, 7, 512)     0                                            
____________________________________________________________________________________________________
res5b_branch2c (Conv2D)          (None, 7, 7, 2048)    1050624                                      
____________________________________________________________________________________________________
bn5b_branch2c (BatchNormalizatio (None, 7, 7, 2048)    8192                                         
____________________________________________________________________________________________________
add_15 (Add)                     (None, 7, 7, 2048)    0                                            
____________________________________________________________________________________________________
activation_46 (Activation)       (None, 7, 7, 2048)    0                                            
____________________________________________________________________________________________________
res5c_branch2a (Conv2D)          (None, 7, 7, 512)     1049088                                      
____________________________________________________________________________________________________
bn5c_branch2a (BatchNormalizatio (None, 7, 7, 512)     2048                                         
____________________________________________________________________________________________________
activation_47 (Activation)       (None, 7, 7, 512)     0                                            
____________________________________________________________________________________________________
res5c_branch2b (Conv2D)          (None, 7, 7, 512)     2359808                                      
____________________________________________________________________________________________________
bn5c_branch2b (BatchNormalizatio (None, 7, 7, 512)     2048                                         
____________________________________________________________________________________________________
activation_48 (Activation)       (None, 7, 7, 512)     0                                            
____________________________________________________________________________________________________
res5c_branch2c (Conv2D)          (None, 7, 7, 2048)    1050624                                      
____________________________________________________________________________________________________
bn5c_branch2c (BatchNormalizatio (None, 7, 7, 2048)    8192                                         
____________________________________________________________________________________________________
add_16 (Add)                     (None, 7, 7, 2048)    0                                            
____________________________________________________________________________________________________
activation_49 (Activation)       (None, 7, 7, 2048)    0                                            
____________________________________________________________________________________________________
avg_pool (AveragePooling2D)      (None, 1, 1, 2048)    0                                            
____________________________________________________________________________________________________
flatten_1 (Flatten)              (None, 2048)          0                                            
____________________________________________________________________________________________________
fc1000 (Dense)                   (None, 1000)          2049000                                      
====================================================================================================
Total params: 25,636,712.0
Trainable params: 25,583,592.0
Non-trainable params: 53,120.0
____________________________________________________________________________________________________

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [19]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [20]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [21]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer: 1% of images in human_files_short have a detected dog, while 100% of images in dog_files_short have a detected dog. The ResNet-50 model is able to detect correctly all the dog images, with only 1% false positive rate on the human images.

In [22]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
def percentage_dog_detected(img_list):
    percent = 100 * sum([1.0 for img_path in img_list if dog_detector(img_path)])/len(img_list)
    print("Percentage of images with detected dog: {}%".format(percent))
    
print("Testing human_files_short- ", end="\t")
percentage_dog_detected(human_files_short)
print("Testing dog_files_short- ", end="\t")
percentage_dog_detected(dog_files_short)
Testing human_files_short- 	Percentage of images with detected dog: 1.0%
Testing dog_files_short- 	Percentage of images with detected dog: 100.0%

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [23]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|███████████████████████████████████████████████████████████████████████████████████| 6680/6680 [00:45<00:00, 145.37it/s]
100%|█████████████████████████████████████████████████████████████████████████████████████| 835/835 [00:05<00:00, 150.22it/s]
100%|█████████████████████████████████████████████████████████████████████████████████████| 836/836 [00:05<00:00, 156.37it/s]
In [24]:
train_tensors.shape
Out[24]:
(6680, 224, 224, 3)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: I started with the hinted architecture to check its performance, which gave a test accuracy of 5%. Added a dropout layer after the final max pooling to reduce overfitting, which increased test accuracy to 6%. Adding another Conv2D layer with 128 filters increased accuracy to 7%. Adding dropout layers after every max pooling layer increased accuracy to 8%. Adding another Conv2D with 256 filters bumped up accuracy to 12%. Decided to double the Conv2D layers at 32, 64, 128 filters with dropout. Dropped the 16 and 256 filters layers as the 256 filters layer lead to decreased accuracy, while dropping the 16 filters layer didn't decrease accuracy significantly. Also increased filter kernel size to 3x3 to capture more detail. This resulted in 14% test accuracy after 20 epochs, and 27-32% test accuracy after 50 epochs.

In [25]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
# Test accuracy: 14.4737% after 20 epochs
# Test accuracy: 32.4163% after 50 epochs
# Test accuracy: 33.2536% after 100 epochs
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 32)      896       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 224, 224, 32)      9248      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 112, 112, 32)      0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 112, 112, 32)      0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 112, 112, 64)      18496     
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 112, 112, 64)      36928     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 56, 56, 64)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 56, 56, 64)        0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 56, 56, 128)       73856     
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 56, 56, 128)       147584    
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 28, 28, 128)       0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 28, 28, 128)       0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 128)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               17157     
=================================================================
Total params: 304,165.0
Trainable params: 304,165.0
Non-trainable params: 0.0
_________________________________________________________________
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
#### Test accuracy: 11.0048% after 20 epochs
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(16, (2, 2), padding='valid', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
#### Test accuracy: 5.3828% after 20 epochs
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(16, (2, 2), padding='valid', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
#### Test accuracy: 6.1005% after 20 epochs
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(16, (2, 2), padding='valid', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (2, 2), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
#### Test accuracy: 7.6555% after 20 epochs
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(16, (2, 2), padding='valid', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(32, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
#### Test accuracy: 8.0144% after 20 epochs
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(16, (2, 2), padding='valid', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(32, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(256, (2, 2), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
#### Test accuracy: 12.3206% after 20 epochs
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(16, (3, 3), padding='same', activation='relu', input_shape=train_tensors.shape[1:]))
model.add(Conv2D(16, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(GlobalAveragePooling2D())
model.add(Dense(len(dog_names), activation='softmax'))

model.summary()
#### Test accuracy: 14.5933% after 20 epochs

Compile the Model

In [26]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
from keras.optimizers import RMSprop
opt = RMSprop(lr=0.0001, decay=1e-6)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [27]:
%%time
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 50

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=2)
Train on 6680 samples, validate on 835 samples
Epoch 1/50
Epoch 00000: val_loss improved from inf to 4.87367, saving model to saved_models/weights.best.from_scratch.hdf5
30s - loss: 4.8904 - acc: 0.0087 - val_loss: 4.8737 - val_acc: 0.0120
Epoch 2/50
Epoch 00001: val_loss improved from 4.87367 to 4.87169, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 4.8783 - acc: 0.0102 - val_loss: 4.8717 - val_acc: 0.0156
Epoch 3/50
Epoch 00002: val_loss improved from 4.87169 to 4.83052, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 4.8528 - acc: 0.0148 - val_loss: 4.8305 - val_acc: 0.0216
Epoch 4/50
Epoch 00003: val_loss improved from 4.83052 to 4.76744, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 4.8045 - acc: 0.0174 - val_loss: 4.7674 - val_acc: 0.0228
Epoch 5/50
Epoch 00004: val_loss improved from 4.76744 to 4.76191, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 4.7326 - acc: 0.0268 - val_loss: 4.7619 - val_acc: 0.0180
Epoch 6/50
Epoch 00005: val_loss improved from 4.76191 to 4.58810, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 4.6321 - acc: 0.0341 - val_loss: 4.5881 - val_acc: 0.0503
Epoch 7/50
Epoch 00006: val_loss improved from 4.58810 to 4.56258, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 4.5255 - acc: 0.0418 - val_loss: 4.5626 - val_acc: 0.0323
Epoch 8/50
Epoch 00007: val_loss improved from 4.56258 to 4.46541, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 4.4338 - acc: 0.0516 - val_loss: 4.4654 - val_acc: 0.0527
Epoch 9/50
Epoch 00008: val_loss improved from 4.46541 to 4.34811, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 4.3461 - acc: 0.0582 - val_loss: 4.3481 - val_acc: 0.0635
Epoch 10/50
Epoch 00009: val_loss improved from 4.34811 to 4.27459, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 4.2566 - acc: 0.0680 - val_loss: 4.2746 - val_acc: 0.0743
Epoch 11/50
Epoch 00010: val_loss improved from 4.27459 to 4.21462, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 4.1596 - acc: 0.0774 - val_loss: 4.2146 - val_acc: 0.0683
Epoch 12/50
Epoch 00011: val_loss improved from 4.21462 to 4.19989, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 4.0588 - acc: 0.0919 - val_loss: 4.1999 - val_acc: 0.0671
Epoch 13/50
Epoch 00012: val_loss improved from 4.19989 to 4.08148, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 3.9765 - acc: 0.0975 - val_loss: 4.0815 - val_acc: 0.0802
Epoch 14/50
Epoch 00013: val_loss improved from 4.08148 to 4.00201, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 3.8844 - acc: 0.1154 - val_loss: 4.0020 - val_acc: 0.0982
Epoch 15/50
Epoch 00014: val_loss did not improve
29s - loss: 3.8088 - acc: 0.1204 - val_loss: 4.6883 - val_acc: 0.0467
Epoch 16/50
Epoch 00015: val_loss improved from 4.00201 to 3.91325, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 3.7272 - acc: 0.1314 - val_loss: 3.9133 - val_acc: 0.1042
Epoch 17/50
Epoch 00016: val_loss improved from 3.91325 to 3.81646, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 3.6290 - acc: 0.1433 - val_loss: 3.8165 - val_acc: 0.1054
Epoch 18/50
Epoch 00017: val_loss did not improve
29s - loss: 3.5529 - acc: 0.1561 - val_loss: 3.8562 - val_acc: 0.1030
Epoch 19/50
Epoch 00018: val_loss improved from 3.81646 to 3.77732, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 3.4911 - acc: 0.1692 - val_loss: 3.7773 - val_acc: 0.1317
Epoch 20/50
Epoch 00019: val_loss did not improve
29s - loss: 3.4046 - acc: 0.1828 - val_loss: 3.7861 - val_acc: 0.1341
Epoch 21/50
Epoch 00020: val_loss improved from 3.77732 to 3.62813, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 3.3516 - acc: 0.1964 - val_loss: 3.6281 - val_acc: 0.1305
Epoch 22/50
Epoch 00021: val_loss improved from 3.62813 to 3.52111, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 3.2850 - acc: 0.2063 - val_loss: 3.5211 - val_acc: 0.1581
Epoch 23/50
Epoch 00022: val_loss improved from 3.52111 to 3.47450, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 3.2250 - acc: 0.2105 - val_loss: 3.4745 - val_acc: 0.1725
Epoch 24/50
Epoch 00023: val_loss did not improve
29s - loss: 3.1578 - acc: 0.2277 - val_loss: 3.5714 - val_acc: 0.1701
Epoch 25/50
Epoch 00024: val_loss improved from 3.47450 to 3.40427, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 3.0976 - acc: 0.2385 - val_loss: 3.4043 - val_acc: 0.1784
Epoch 26/50
Epoch 00025: val_loss did not improve
28s - loss: 3.0366 - acc: 0.2509 - val_loss: 3.6036 - val_acc: 0.1868
Epoch 27/50
Epoch 00026: val_loss improved from 3.40427 to 3.28338, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 2.9802 - acc: 0.2546 - val_loss: 3.2834 - val_acc: 0.2096
Epoch 28/50
Epoch 00027: val_loss did not improve
29s - loss: 2.9407 - acc: 0.2675 - val_loss: 3.4658 - val_acc: 0.1832
Epoch 29/50
Epoch 00028: val_loss did not improve
29s - loss: 2.8906 - acc: 0.2784 - val_loss: 3.3166 - val_acc: 0.2228
Epoch 30/50
Epoch 00029: val_loss did not improve
29s - loss: 2.8347 - acc: 0.2816 - val_loss: 3.7191 - val_acc: 0.1940
Epoch 31/50
Epoch 00030: val_loss did not improve
29s - loss: 2.7748 - acc: 0.2966 - val_loss: 3.3120 - val_acc: 0.2275
Epoch 32/50
Epoch 00031: val_loss improved from 3.28338 to 3.25648, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 2.7367 - acc: 0.3135 - val_loss: 3.2565 - val_acc: 0.2228
Epoch 33/50
Epoch 00032: val_loss improved from 3.25648 to 3.19861, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 2.6826 - acc: 0.3231 - val_loss: 3.1986 - val_acc: 0.2323
Epoch 34/50
Epoch 00033: val_loss improved from 3.19861 to 3.19665, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 2.6380 - acc: 0.3253 - val_loss: 3.1967 - val_acc: 0.2419
Epoch 35/50
Epoch 00034: val_loss did not improve
28s - loss: 2.5883 - acc: 0.3424 - val_loss: 3.2011 - val_acc: 0.2719
Epoch 36/50
Epoch 00035: val_loss did not improve
28s - loss: 2.5389 - acc: 0.3527 - val_loss: 3.2944 - val_acc: 0.2671
Epoch 37/50
Epoch 00036: val_loss did not improve
28s - loss: 2.4893 - acc: 0.3608 - val_loss: 3.2574 - val_acc: 0.2263
Epoch 38/50
Epoch 00037: val_loss improved from 3.19665 to 3.06739, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 2.4634 - acc: 0.3719 - val_loss: 3.0674 - val_acc: 0.2719
Epoch 39/50
Epoch 00038: val_loss did not improve
28s - loss: 2.4153 - acc: 0.3814 - val_loss: 3.2464 - val_acc: 0.2611
Epoch 40/50
Epoch 00039: val_loss did not improve
28s - loss: 2.3592 - acc: 0.3877 - val_loss: 3.1031 - val_acc: 0.2731
Epoch 41/50
Epoch 00040: val_loss improved from 3.06739 to 3.02307, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 2.3116 - acc: 0.3972 - val_loss: 3.0231 - val_acc: 0.2874
Epoch 42/50
Epoch 00041: val_loss did not improve
28s - loss: 2.2758 - acc: 0.4069 - val_loss: 3.0901 - val_acc: 0.2719
Epoch 43/50
Epoch 00042: val_loss did not improve
28s - loss: 2.2509 - acc: 0.4150 - val_loss: 3.2525 - val_acc: 0.2515
Epoch 44/50
Epoch 00043: val_loss improved from 3.02307 to 2.99045, saving model to saved_models/weights.best.from_scratch.hdf5
28s - loss: 2.2048 - acc: 0.4192 - val_loss: 2.9904 - val_acc: 0.2982
Epoch 45/50
Epoch 00044: val_loss did not improve
28s - loss: 2.1592 - acc: 0.4283 - val_loss: 3.6915 - val_acc: 0.2240
Epoch 46/50
Epoch 00045: val_loss improved from 2.99045 to 2.90434, saving model to saved_models/weights.best.from_scratch.hdf5
29s - loss: 2.1340 - acc: 0.4365 - val_loss: 2.9043 - val_acc: 0.3030
Epoch 47/50
Epoch 00046: val_loss did not improve
28s - loss: 2.0848 - acc: 0.4478 - val_loss: 3.1456 - val_acc: 0.2635
Epoch 48/50
Epoch 00047: val_loss did not improve
28s - loss: 2.0382 - acc: 0.4522 - val_loss: 3.0250 - val_acc: 0.3114
Epoch 49/50
Epoch 00048: val_loss did not improve
29s - loss: 2.0038 - acc: 0.4650 - val_loss: 3.2198 - val_acc: 0.2778
Epoch 50/50
Epoch 00049: val_loss did not improve
29s - loss: 1.9922 - acc: 0.4707 - val_loss: 3.2720 - val_acc: 0.3066
Wall time: 24min 11s

Load the Model with the Best Validation Loss

In [28]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [29]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 31.5789%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [30]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [31]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [32]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [33]:
%%time
from keras.callbacks import ModelCheckpoint 

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6620/6680 [============================>.] - ETA: 100s - loss: 15.3424 - acc: 0.0000e+00 - ETA: 19s - loss: 14.9903 - acc: 0.0083      - ETA: 9s - loss: 14.7042 - acc: 0.0250  - ETA: 5s - loss: 14.6677 - acc: 0.0229 - ETA: 4s - loss: 14.5632 - acc: 0.0221 - ETA: 3s - loss: 14.5568 - acc: 0.0267 - ETA: 3s - loss: 14.4979 - acc: 0.0302 - ETA: 2s - loss: 14.3364 - acc: 0.0347 - ETA: 2s - loss: 14.2116 - acc: 0.0394 - ETA: 2s - loss: 14.0667 - acc: 0.0450 - ETA: 2s - loss: 13.9754 - acc: 0.0478 - ETA: 2s - loss: 13.9171 - acc: 0.0505 - ETA: 1s - loss: 13.8227 - acc: 0.0542 - ETA: 1s - loss: 13.8039 - acc: 0.0543 - ETA: 1s - loss: 13.7209 - acc: 0.0563 - ETA: 1s - loss: 13.6576 - acc: 0.0577 - ETA: 1s - loss: 13.5653 - acc: 0.0611 - ETA: 1s - loss: 13.5048 - acc: 0.0630 - ETA: 1s - loss: 13.4358 - acc: 0.0662 - ETA: 1s - loss: 13.3450 - acc: 0.0702 - ETA: 1s - loss: 13.2737 - acc: 0.0741 - ETA: 0s - loss: 13.1760 - acc: 0.0782 - ETA: 0s - loss: 13.1078 - acc: 0.0811 - ETA: 0s - loss: 13.0503 - acc: 0.0848 - ETA: 0s - loss: 13.0095 - acc: 0.0871 - ETA: 0s - loss: 12.9161 - acc: 0.0921 - ETA: 0s - loss: 12.8563 - acc: 0.0959 - ETA: 0s - loss: 12.7896 - acc: 0.0988 - ETA: 0s - loss: 12.7416 - acc: 0.1015 - ETA: 0s - loss: 12.6522 - acc: 0.1066 - ETA: 0s - loss: 12.6123 - acc: 0.1097 - ETA: 0s - loss: 12.5918 - acc: 0.1104 - ETA: 0s - loss: 12.5630 - acc: 0.1118 - ETA: 0s - loss: 12.5080 - acc: 0.1145 - ETA: 0s - loss: 12.4843 - acc: 0.1162 - ETA: 0s - loss: 12.4437 - acc: 0.1193Epoch 00000: val_loss improved from inf to 10.89270, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s - loss: 12.4269 - acc: 0.1208 - val_loss: 10.8927 - val_acc: 0.2323
Epoch 2/20
6540/6680 [============================>.] - ETA: 3s - loss: 9.8310 - acc: 0.3500 - ETA: 2s - loss: 10.3437 - acc: 0.2722 - ETA: 1s - loss: 10.2433 - acc: 0.2895 - ETA: 1s - loss: 10.2383 - acc: 0.2776 - ETA: 1s - loss: 10.1164 - acc: 0.2808 - ETA: 1s - loss: 10.0991 - acc: 0.2806 - ETA: 1s - loss: 10.2642 - acc: 0.2737 - ETA: 1s - loss: 10.2756 - acc: 0.2754 - ETA: 1s - loss: 10.2324 - acc: 0.2769 - ETA: 1s - loss: 10.2548 - acc: 0.2770 - ETA: 1s - loss: 10.2130 - acc: 0.2797 - ETA: 1s - loss: 10.2087 - acc: 0.2790 - ETA: 1s - loss: 10.2276 - acc: 0.2789 - ETA: 1s - loss: 10.2678 - acc: 0.2764 - ETA: 1s - loss: 10.3277 - acc: 0.2742 - ETA: 1s - loss: 10.3671 - acc: 0.2718 - ETA: 0s - loss: 10.3464 - acc: 0.2727 - ETA: 0s - loss: 10.3364 - acc: 0.2750 - ETA: 0s - loss: 10.3035 - acc: 0.2765 - ETA: 0s - loss: 10.3120 - acc: 0.2753 - ETA: 0s - loss: 10.3485 - acc: 0.2729 - ETA: 0s - loss: 10.3232 - acc: 0.2740 - ETA: 0s - loss: 10.3223 - acc: 0.2735 - ETA: 0s - loss: 10.3197 - acc: 0.2738 - ETA: 0s - loss: 10.3107 - acc: 0.2742 - ETA: 0s - loss: 10.3113 - acc: 0.2746 - ETA: 0s - loss: 10.3549 - acc: 0.2728 - ETA: 0s - loss: 10.3452 - acc: 0.2737 - ETA: 0s - loss: 10.3404 - acc: 0.2743 - ETA: 0s - loss: 10.3397 - acc: 0.2746 - ETA: 0s - loss: 10.3426 - acc: 0.2739 - ETA: 0s - loss: 10.3177 - acc: 0.2754 - ETA: 0s - loss: 10.3368 - acc: 0.2743 - ETA: 0s - loss: 10.3581 - acc: 0.2733 - ETA: 0s - loss: 10.3389 - acc: 0.2749Epoch 00001: val_loss improved from 10.89270 to 10.15088, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.3409 - acc: 0.2750 - val_loss: 10.1509 - val_acc: 0.2934
Epoch 3/20
6560/6680 [============================>.] - ETA: 2s - loss: 9.8398 - acc: 0.3500 - ETA: 1s - loss: 9.6521 - acc: 0.3455 - ETA: 1s - loss: 10.0935 - acc: 0.3143 - ETA: 1s - loss: 9.9053 - acc: 0.3210  - ETA: 1s - loss: 9.7300 - acc: 0.3341 - ETA: 1s - loss: 9.7785 - acc: 0.3308 - ETA: 1s - loss: 9.8581 - acc: 0.3218 - ETA: 1s - loss: 9.8231 - acc: 0.3250 - ETA: 1s - loss: 9.8205 - acc: 0.3274 - ETA: 1s - loss: 9.8041 - acc: 0.3288 - ETA: 1s - loss: 9.8495 - acc: 0.3275 - ETA: 1s - loss: 9.8565 - acc: 0.3248 - ETA: 1s - loss: 9.8283 - acc: 0.3281 - ETA: 1s - loss: 9.7298 - acc: 0.3344 - ETA: 1s - loss: 9.7527 - acc: 0.3337 - ETA: 0s - loss: 9.7238 - acc: 0.3362 - ETA: 0s - loss: 9.7188 - acc: 0.3367 - ETA: 0s - loss: 9.7428 - acc: 0.3337 - ETA: 0s - loss: 9.7379 - acc: 0.3351 - ETA: 0s - loss: 9.7844 - acc: 0.3322 - ETA: 0s - loss: 9.8078 - acc: 0.3321 - ETA: 0s - loss: 9.7913 - acc: 0.3329 - ETA: 0s - loss: 9.8187 - acc: 0.3313 - ETA: 0s - loss: 9.8130 - acc: 0.3303 - ETA: 0s - loss: 9.8226 - acc: 0.3295 - ETA: 0s - loss: 9.8179 - acc: 0.3305 - ETA: 0s - loss: 9.8142 - acc: 0.3305 - ETA: 0s - loss: 9.8184 - acc: 0.3306 - ETA: 0s - loss: 9.8308 - acc: 0.3297 - ETA: 0s - loss: 9.8311 - acc: 0.3288 - ETA: 0s - loss: 9.8170 - acc: 0.3287 - ETA: 0s - loss: 9.7986 - acc: 0.3289 - ETA: 0s - loss: 9.7701 - acc: 0.3311 - ETA: 0s - loss: 9.7572 - acc: 0.3319Epoch 00002: val_loss improved from 10.15088 to 9.80459, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.7405 - acc: 0.3334 - val_loss: 9.8046 - val_acc: 0.3018
Epoch 4/20
6620/6680 [============================>.] - ETA: 2s - loss: 9.7271 - acc: 0.3500 - ETA: 1s - loss: 8.8493 - acc: 0.3818 - ETA: 1s - loss: 8.9877 - acc: 0.3762 - ETA: 1s - loss: 9.3920 - acc: 0.3581 - ETA: 1s - loss: 9.2150 - acc: 0.3659 - ETA: 1s - loss: 9.1841 - acc: 0.3706 - ETA: 1s - loss: 9.2296 - acc: 0.3648 - ETA: 1s - loss: 9.3021 - acc: 0.3641 - ETA: 1s - loss: 9.3500 - acc: 0.3648 - ETA: 1s - loss: 9.3721 - acc: 0.3648 - ETA: 1s - loss: 9.2647 - acc: 0.3713 - ETA: 1s - loss: 9.2942 - acc: 0.3689 - ETA: 1s - loss: 9.3838 - acc: 0.3645 - ETA: 1s - loss: 9.3383 - acc: 0.3679 - ETA: 1s - loss: 9.3261 - acc: 0.3683 - ETA: 0s - loss: 9.3025 - acc: 0.3701 - ETA: 0s - loss: 9.3353 - acc: 0.3688 - ETA: 0s - loss: 9.3607 - acc: 0.3669 - ETA: 0s - loss: 9.3321 - acc: 0.3689 - ETA: 0s - loss: 9.3353 - acc: 0.3697 - ETA: 0s - loss: 9.3593 - acc: 0.3687 - ETA: 0s - loss: 9.3743 - acc: 0.3681 - ETA: 0s - loss: 9.3681 - acc: 0.3677 - ETA: 0s - loss: 9.3422 - acc: 0.3704 - ETA: 0s - loss: 9.3331 - acc: 0.3714 - ETA: 0s - loss: 9.3133 - acc: 0.3724 - ETA: 0s - loss: 9.3132 - acc: 0.3720 - ETA: 0s - loss: 9.3117 - acc: 0.3725 - ETA: 0s - loss: 9.2807 - acc: 0.3749 - ETA: 0s - loss: 9.2937 - acc: 0.3738 - ETA: 0s - loss: 9.2813 - acc: 0.3740 - ETA: 0s - loss: 9.2580 - acc: 0.3755 - ETA: 0s - loss: 9.2458 - acc: 0.3762 - ETA: 0s - loss: 9.2635 - acc: 0.3743Epoch 00003: val_loss improved from 9.80459 to 9.41524, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.2654 - acc: 0.3744 - val_loss: 9.4152 - val_acc: 0.3329
Epoch 5/20
6500/6680 [============================>.] - ETA: 2s - loss: 6.4831 - acc: 0.6000 - ETA: 1s - loss: 9.2242 - acc: 0.3950 - ETA: 1s - loss: 9.0327 - acc: 0.4125 - ETA: 1s - loss: 8.8197 - acc: 0.4300 - ETA: 1s - loss: 8.9724 - acc: 0.4218 - ETA: 1s - loss: 9.0335 - acc: 0.4153 - ETA: 1s - loss: 8.9881 - acc: 0.4169 - ETA: 1s - loss: 9.1042 - acc: 0.4101 - ETA: 1s - loss: 9.0419 - acc: 0.4103 - ETA: 1s - loss: 8.9755 - acc: 0.4115 - ETA: 1s - loss: 8.9820 - acc: 0.4094 - ETA: 1s - loss: 8.9800 - acc: 0.4105 - ETA: 1s - loss: 9.0131 - acc: 0.4083 - ETA: 1s - loss: 8.9717 - acc: 0.4096 - ETA: 1s - loss: 8.9086 - acc: 0.4122 - ETA: 1s - loss: 8.8777 - acc: 0.4147 - ETA: 0s - loss: 8.9035 - acc: 0.4131 - ETA: 0s - loss: 8.9145 - acc: 0.4129 - ETA: 0s - loss: 8.9511 - acc: 0.4112 - ETA: 0s - loss: 8.9353 - acc: 0.4125 - ETA: 0s - loss: 8.8905 - acc: 0.4149 - ETA: 0s - loss: 8.9158 - acc: 0.4142 - ETA: 0s - loss: 8.9229 - acc: 0.4131 - ETA: 0s - loss: 8.9324 - acc: 0.4119 - ETA: 0s - loss: 8.9118 - acc: 0.4139 - ETA: 0s - loss: 8.9118 - acc: 0.4140 - ETA: 0s - loss: 8.9366 - acc: 0.4117 - ETA: 0s - loss: 8.9031 - acc: 0.4135 - ETA: 0s - loss: 8.9145 - acc: 0.4128 - ETA: 0s - loss: 8.9050 - acc: 0.4139 - ETA: 0s - loss: 8.9097 - acc: 0.4137 - ETA: 0s - loss: 8.9104 - acc: 0.4139 - ETA: 0s - loss: 8.9137 - acc: 0.4131 - ETA: 0s - loss: 8.9481 - acc: 0.4103Epoch 00004: val_loss improved from 9.41524 to 9.34881, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.9813 - acc: 0.4085 - val_loss: 9.3488 - val_acc: 0.3437
Epoch 6/20
6540/6680 [============================>.] - ETA: 1s - loss: 12.0887 - acc: 0.2500 - ETA: 1s - loss: 8.7113 - acc: 0.4227  - ETA: 1s - loss: 8.5589 - acc: 0.4300 - ETA: 1s - loss: 8.8721 - acc: 0.4183 - ETA: 1s - loss: 8.7340 - acc: 0.4300 - ETA: 1s - loss: 8.9068 - acc: 0.4190 - ETA: 1s - loss: 8.6434 - acc: 0.4350 - ETA: 1s - loss: 8.6873 - acc: 0.4329 - ETA: 1s - loss: 8.8086 - acc: 0.4281 - ETA: 1s - loss: 8.8313 - acc: 0.4278 - ETA: 1s - loss: 8.8262 - acc: 0.4285 - ETA: 1s - loss: 8.8619 - acc: 0.4255 - ETA: 1s - loss: 8.8635 - acc: 0.4248 - ETA: 1s - loss: 8.8797 - acc: 0.4236 - ETA: 1s - loss: 8.8530 - acc: 0.4248 - ETA: 0s - loss: 8.8726 - acc: 0.4230 - ETA: 0s - loss: 8.9388 - acc: 0.4187 - ETA: 0s - loss: 8.9918 - acc: 0.4161 - ETA: 0s - loss: 8.9848 - acc: 0.4157 - ETA: 0s - loss: 8.9842 - acc: 0.4160 - ETA: 0s - loss: 8.9659 - acc: 0.4173 - ETA: 0s - loss: 8.9505 - acc: 0.4184 - ETA: 0s - loss: 8.9904 - acc: 0.4164 - ETA: 0s - loss: 8.9803 - acc: 0.4178 - ETA: 0s - loss: 8.9996 - acc: 0.4160 - ETA: 0s - loss: 8.9958 - acc: 0.4165 - ETA: 0s - loss: 8.9868 - acc: 0.4167 - ETA: 0s - loss: 8.9413 - acc: 0.4196 - ETA: 0s - loss: 8.9561 - acc: 0.4178 - ETA: 0s - loss: 8.9616 - acc: 0.4173 - ETA: 0s - loss: 8.9375 - acc: 0.4184 - ETA: 0s - loss: 8.9164 - acc: 0.4196 - ETA: 0s - loss: 8.9436 - acc: 0.4180 - ETA: 0s - loss: 8.9331 - acc: 0.4187Epoch 00005: val_loss improved from 9.34881 to 9.29635, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.9212 - acc: 0.4195 - val_loss: 9.2963 - val_acc: 0.3593
Epoch 7/20
6580/6680 [============================>.] - ETA: 1s - loss: 6.4482 - acc: 0.6000 - ETA: 1s - loss: 8.4028 - acc: 0.4636 - ETA: 1s - loss: 8.8200 - acc: 0.4381 - ETA: 1s - loss: 8.7944 - acc: 0.4371 - ETA: 1s - loss: 8.6310 - acc: 0.4463 - ETA: 1s - loss: 8.4483 - acc: 0.4578 - ETA: 1s - loss: 8.5923 - acc: 0.4508 - ETA: 1s - loss: 8.5571 - acc: 0.4528 - ETA: 1s - loss: 8.6082 - acc: 0.4512 - ETA: 1s - loss: 8.5767 - acc: 0.4533 - ETA: 1s - loss: 8.6045 - acc: 0.4520 - ETA: 1s - loss: 8.5314 - acc: 0.4563 - ETA: 1s - loss: 8.5618 - acc: 0.4541 - ETA: 1s - loss: 8.5971 - acc: 0.4508 - ETA: 1s - loss: 8.5923 - acc: 0.4493 - ETA: 0s - loss: 8.6404 - acc: 0.4467 - ETA: 0s - loss: 8.6953 - acc: 0.4432 - ETA: 0s - loss: 8.7049 - acc: 0.4418 - ETA: 0s - loss: 8.7571 - acc: 0.4376 - ETA: 0s - loss: 8.7545 - acc: 0.4359 - ETA: 0s - loss: 8.7954 - acc: 0.4333 - ETA: 0s - loss: 8.8002 - acc: 0.4336 - ETA: 0s - loss: 8.7966 - acc: 0.4336 - ETA: 0s - loss: 8.8077 - acc: 0.4322 - ETA: 0s - loss: 8.8483 - acc: 0.4297 - ETA: 0s - loss: 8.8036 - acc: 0.4317 - ETA: 0s - loss: 8.8252 - acc: 0.4305 - ETA: 0s - loss: 8.8305 - acc: 0.4303 - ETA: 0s - loss: 8.8727 - acc: 0.4276 - ETA: 0s - loss: 8.8991 - acc: 0.4253 - ETA: 0s - loss: 8.8689 - acc: 0.4265 - ETA: 0s - loss: 8.8219 - acc: 0.4289 - ETA: 0s - loss: 8.8123 - acc: 0.4295 - ETA: 0s - loss: 8.8226 - acc: 0.4293Epoch 00006: val_loss improved from 9.29635 to 9.14661, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.8187 - acc: 0.4298 - val_loss: 9.1466 - val_acc: 0.3665
Epoch 8/20
6520/6680 [============================>.] - ETA: 2s - loss: 6.7571 - acc: 0.5500 - ETA: 1s - loss: 7.7959 - acc: 0.5050 - ETA: 1s - loss: 8.1221 - acc: 0.4800 - ETA: 1s - loss: 8.3402 - acc: 0.4650 - ETA: 1s - loss: 8.4529 - acc: 0.4550 - ETA: 1s - loss: 8.3897 - acc: 0.4600 - ETA: 1s - loss: 8.5225 - acc: 0.4508 - ETA: 1s - loss: 8.5355 - acc: 0.4450 - ETA: 1s - loss: 8.5518 - acc: 0.4438 - ETA: 1s - loss: 8.6118 - acc: 0.4417 - ETA: 1s - loss: 8.5214 - acc: 0.4455 - ETA: 1s - loss: 8.5106 - acc: 0.4482 - ETA: 1s - loss: 8.5499 - acc: 0.4471 - ETA: 1s - loss: 8.5700 - acc: 0.4465 - ETA: 1s - loss: 8.5410 - acc: 0.4478 - ETA: 0s - loss: 8.5766 - acc: 0.4459 - ETA: 0s - loss: 8.6029 - acc: 0.4443 - ETA: 0s - loss: 8.6380 - acc: 0.4429 - ETA: 0s - loss: 8.6545 - acc: 0.4421 - ETA: 0s - loss: 8.6285 - acc: 0.4441 - ETA: 0s - loss: 8.6684 - acc: 0.4409 - ETA: 0s - loss: 8.6735 - acc: 0.4409 - ETA: 0s - loss: 8.7075 - acc: 0.4382 - ETA: 0s - loss: 8.7086 - acc: 0.4374 - ETA: 0s - loss: 8.7101 - acc: 0.4376 - ETA: 0s - loss: 8.6905 - acc: 0.4391 - ETA: 0s - loss: 8.7058 - acc: 0.4385 - ETA: 0s - loss: 8.6594 - acc: 0.4418 - ETA: 0s - loss: 8.6696 - acc: 0.4413 - ETA: 0s - loss: 8.6961 - acc: 0.4397 - ETA: 0s - loss: 8.6929 - acc: 0.4401 - ETA: 0s - loss: 8.6655 - acc: 0.4418 - ETA: 0s - loss: 8.6760 - acc: 0.4415 - ETA: 0s - loss: 8.6652 - acc: 0.4420Epoch 00007: val_loss improved from 9.14661 to 9.07987, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6686 - acc: 0.4416 - val_loss: 9.0799 - val_acc: 0.3737
Epoch 9/20
6500/6680 [============================>.] - ETA: 1s - loss: 8.8788 - acc: 0.4500 - ETA: 1s - loss: 9.1058 - acc: 0.4273 - ETA: 1s - loss: 8.6244 - acc: 0.4500 - ETA: 1s - loss: 8.6302 - acc: 0.4532 - ETA: 1s - loss: 8.6137 - acc: 0.4560 - ETA: 1s - loss: 8.6753 - acc: 0.4529 - ETA: 1s - loss: 8.6893 - acc: 0.4524 - ETA: 1s - loss: 8.6053 - acc: 0.4548 - ETA: 1s - loss: 8.7453 - acc: 0.4470 - ETA: 1s - loss: 8.7436 - acc: 0.4457 - ETA: 1s - loss: 8.7831 - acc: 0.4427 - ETA: 1s - loss: 8.7987 - acc: 0.4416 - ETA: 1s - loss: 8.8399 - acc: 0.4386 - ETA: 1s - loss: 8.8188 - acc: 0.4392 - ETA: 0s - loss: 8.7856 - acc: 0.4410 - ETA: 0s - loss: 8.7472 - acc: 0.4426 - ETA: 0s - loss: 8.7310 - acc: 0.4427 - ETA: 0s - loss: 8.6858 - acc: 0.4460 - ETA: 0s - loss: 8.7182 - acc: 0.4443 - ETA: 0s - loss: 8.6812 - acc: 0.4472 - ETA: 0s - loss: 8.6713 - acc: 0.4483 - ETA: 0s - loss: 8.7048 - acc: 0.4465 - ETA: 0s - loss: 8.7148 - acc: 0.4458 - ETA: 0s - loss: 8.7255 - acc: 0.4451 - ETA: 0s - loss: 8.6728 - acc: 0.4482 - ETA: 0s - loss: 8.6614 - acc: 0.4492 - ETA: 0s - loss: 8.6585 - acc: 0.4492 - ETA: 0s - loss: 8.6504 - acc: 0.4495 - ETA: 0s - loss: 8.6338 - acc: 0.4495 - ETA: 0s - loss: 8.6361 - acc: 0.4485 - ETA: 0s - loss: 8.6230 - acc: 0.4485 - ETA: 0s - loss: 8.5992 - acc: 0.4503 - ETA: 0s - loss: 8.5833 - acc: 0.4509Epoch 00008: val_loss improved from 9.07987 to 8.93966, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.5937 - acc: 0.4506 - val_loss: 8.9397 - val_acc: 0.3808
Epoch 10/20
6480/6680 [============================>.] - ETA: 2s - loss: 8.0591 - acc: 0.5000 - ETA: 1s - loss: 9.1601 - acc: 0.4250 - ETA: 1s - loss: 8.4505 - acc: 0.4725 - ETA: 1s - loss: 8.2846 - acc: 0.4783 - ETA: 1s - loss: 8.3153 - acc: 0.4725 - ETA: 1s - loss: 8.3284 - acc: 0.4724 - ETA: 1s - loss: 8.3301 - acc: 0.4720 - ETA: 1s - loss: 8.2492 - acc: 0.4783 - ETA: 1s - loss: 8.2562 - acc: 0.4778 - ETA: 1s - loss: 8.3353 - acc: 0.4736 - ETA: 1s - loss: 8.3520 - acc: 0.4727 - ETA: 1s - loss: 8.3213 - acc: 0.4750 - ETA: 1s - loss: 8.3676 - acc: 0.4712 - ETA: 1s - loss: 8.3879 - acc: 0.4701 - ETA: 1s - loss: 8.4773 - acc: 0.4650 - ETA: 0s - loss: 8.5013 - acc: 0.4633 - ETA: 0s - loss: 8.4895 - acc: 0.4643 - ETA: 0s - loss: 8.5028 - acc: 0.4636 - ETA: 0s - loss: 8.4899 - acc: 0.4643 - ETA: 0s - loss: 8.5299 - acc: 0.4616 - ETA: 0s - loss: 8.5401 - acc: 0.4610 - ETA: 0s - loss: 8.5525 - acc: 0.4602 - ETA: 0s - loss: 8.5463 - acc: 0.4605 - ETA: 0s - loss: 8.5482 - acc: 0.4604 - ETA: 0s - loss: 8.5561 - acc: 0.4594 - ETA: 0s - loss: 8.5691 - acc: 0.4584 - ETA: 0s - loss: 8.5540 - acc: 0.4593 - ETA: 0s - loss: 8.5610 - acc: 0.4591 - ETA: 0s - loss: 8.5390 - acc: 0.4602 - ETA: 0s - loss: 8.5213 - acc: 0.4616 - ETA: 0s - loss: 8.5239 - acc: 0.4616 - ETA: 0s - loss: 8.5035 - acc: 0.4627 - ETA: 0s - loss: 8.4981 - acc: 0.4629 - ETA: 0s - loss: 8.5115 - acc: 0.4619Epoch 00009: val_loss improved from 8.93966 to 8.93559, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.5065 - acc: 0.4618 - val_loss: 8.9356 - val_acc: 0.3844
Epoch 11/20
6560/6680 [============================>.] - ETA: 2s - loss: 7.2533 - acc: 0.5500 - ETA: 1s - loss: 8.4342 - acc: 0.4727 - ETA: 1s - loss: 8.2683 - acc: 0.4810 - ETA: 1s - loss: 8.0650 - acc: 0.4903 - ETA: 1s - loss: 8.2774 - acc: 0.4786 - ETA: 1s - loss: 8.3039 - acc: 0.4750 - ETA: 1s - loss: 8.2012 - acc: 0.4823 - ETA: 1s - loss: 8.3427 - acc: 0.4743 - ETA: 1s - loss: 8.4180 - acc: 0.4689 - ETA: 1s - loss: 8.5036 - acc: 0.4641 - ETA: 1s - loss: 8.5054 - acc: 0.4627 - ETA: 1s - loss: 8.5432 - acc: 0.4603 - ETA: 1s - loss: 8.5205 - acc: 0.4607 - ETA: 1s - loss: 8.5390 - acc: 0.4595 - ETA: 1s - loss: 8.4844 - acc: 0.4627 - ETA: 0s - loss: 8.5242 - acc: 0.4603 - ETA: 0s - loss: 8.4511 - acc: 0.4646 - ETA: 0s - loss: 8.4794 - acc: 0.4626 - ETA: 0s - loss: 8.4854 - acc: 0.4625 - ETA: 0s - loss: 8.4645 - acc: 0.4639 - ETA: 0s - loss: 8.4267 - acc: 0.4658 - ETA: 0s - loss: 8.4285 - acc: 0.4655 - ETA: 0s - loss: 8.4721 - acc: 0.4627 - ETA: 0s - loss: 8.4482 - acc: 0.4641 - ETA: 0s - loss: 8.4438 - acc: 0.4646 - ETA: 0s - loss: 8.4481 - acc: 0.4640 - ETA: 0s - loss: 8.4544 - acc: 0.4637 - ETA: 0s - loss: 8.4129 - acc: 0.4660 - ETA: 0s - loss: 8.4293 - acc: 0.4646 - ETA: 0s - loss: 8.4293 - acc: 0.4642 - ETA: 0s - loss: 8.4441 - acc: 0.4633 - ETA: 0s - loss: 8.4371 - acc: 0.4638 - ETA: 0s - loss: 8.4527 - acc: 0.4624 - ETA: 0s - loss: 8.4240 - acc: 0.4643Epoch 00010: val_loss improved from 8.93559 to 8.80199, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.4170 - acc: 0.4645 - val_loss: 8.8020 - val_acc: 0.3880
Epoch 12/20
6500/6680 [============================>.] - ETA: 1s - loss: 8.9589 - acc: 0.4000 - ETA: 1s - loss: 7.9317 - acc: 0.5000 - ETA: 1s - loss: 8.3528 - acc: 0.4690 - ETA: 1s - loss: 8.3030 - acc: 0.4726 - ETA: 1s - loss: 8.3612 - acc: 0.4683 - ETA: 1s - loss: 8.3688 - acc: 0.4676 - ETA: 1s - loss: 8.1388 - acc: 0.4828 - ETA: 1s - loss: 8.1319 - acc: 0.4831 - ETA: 1s - loss: 8.1165 - acc: 0.4840 - ETA: 1s - loss: 8.2078 - acc: 0.4791 - ETA: 1s - loss: 8.2149 - acc: 0.4787 - ETA: 1s - loss: 8.2275 - acc: 0.4777 - ETA: 1s - loss: 8.2280 - acc: 0.4783 - ETA: 1s - loss: 8.2445 - acc: 0.4762 - ETA: 1s - loss: 8.2511 - acc: 0.4746 - ETA: 0s - loss: 8.2182 - acc: 0.4773 - ETA: 0s - loss: 8.2737 - acc: 0.4741 - ETA: 0s - loss: 8.2443 - acc: 0.4756 - ETA: 0s - loss: 8.2532 - acc: 0.4756 - ETA: 0s - loss: 8.2717 - acc: 0.4743 - ETA: 0s - loss: 8.2825 - acc: 0.4733 - ETA: 0s - loss: 8.2397 - acc: 0.4760 - ETA: 0s - loss: 8.2077 - acc: 0.4775 - ETA: 0s - loss: 8.1759 - acc: 0.4796 - ETA: 0s - loss: 8.2388 - acc: 0.4754 - ETA: 0s - loss: 8.2684 - acc: 0.4734 - ETA: 0s - loss: 8.2527 - acc: 0.4746 - ETA: 0s - loss: 8.2517 - acc: 0.4743 - ETA: 0s - loss: 8.2558 - acc: 0.4743 - ETA: 0s - loss: 8.2472 - acc: 0.4753 - ETA: 0s - loss: 8.2476 - acc: 0.4753 - ETA: 0s - loss: 8.2492 - acc: 0.4751 - ETA: 0s - loss: 8.2311 - acc: 0.4763 - ETA: 0s - loss: 8.2217 - acc: 0.4769Epoch 00011: val_loss improved from 8.80199 to 8.73700, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.2234 - acc: 0.4769 - val_loss: 8.7370 - val_acc: 0.3964
Epoch 13/20
6600/6680 [============================>.] - ETA: 2s - loss: 7.0776 - acc: 0.5000 - ETA: 1s - loss: 7.7853 - acc: 0.5045 - ETA: 1s - loss: 8.0630 - acc: 0.4881 - ETA: 1s - loss: 8.1846 - acc: 0.4806 - ETA: 1s - loss: 8.2691 - acc: 0.4768 - ETA: 1s - loss: 8.3192 - acc: 0.4721 - ETA: 1s - loss: 8.2641 - acc: 0.4758 - ETA: 1s - loss: 8.1748 - acc: 0.4799 - ETA: 1s - loss: 8.0530 - acc: 0.4849 - ETA: 1s - loss: 8.0290 - acc: 0.4871 - ETA: 1s - loss: 8.0561 - acc: 0.4864 - ETA: 1s - loss: 8.1518 - acc: 0.4814 - ETA: 1s - loss: 8.0818 - acc: 0.4858 - ETA: 1s - loss: 8.1186 - acc: 0.4831 - ETA: 0s - loss: 8.0783 - acc: 0.4857 - ETA: 0s - loss: 8.0964 - acc: 0.4843 - ETA: 0s - loss: 8.0785 - acc: 0.4855 - ETA: 0s - loss: 8.0596 - acc: 0.4872 - ETA: 0s - loss: 8.0601 - acc: 0.4874 - ETA: 0s - loss: 8.0716 - acc: 0.4865 - ETA: 0s - loss: 8.1001 - acc: 0.4844 - ETA: 0s - loss: 8.1412 - acc: 0.4821 - ETA: 0s - loss: 8.1562 - acc: 0.4809 - ETA: 0s - loss: 8.1560 - acc: 0.4813 - ETA: 0s - loss: 8.1637 - acc: 0.4807 - ETA: 0s - loss: 8.1708 - acc: 0.4802 - ETA: 0s - loss: 8.2049 - acc: 0.4784 - ETA: 0s - loss: 8.2205 - acc: 0.4775 - ETA: 0s - loss: 8.1808 - acc: 0.4804 - ETA: 0s - loss: 8.1604 - acc: 0.4813 - ETA: 0s - loss: 8.1553 - acc: 0.4819 - ETA: 0s - loss: 8.1579 - acc: 0.4810 - ETA: 0s - loss: 8.1537 - acc: 0.4813 - ETA: 0s - loss: 8.1593 - acc: 0.4809Epoch 00012: val_loss improved from 8.73700 to 8.66738, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.1558 - acc: 0.4811 - val_loss: 8.6674 - val_acc: 0.4048
Epoch 14/20
6660/6680 [============================>.] - ETA: 2s - loss: 8.9351 - acc: 0.4000 - ETA: 1s - loss: 7.9387 - acc: 0.4955 - ETA: 1s - loss: 7.8203 - acc: 0.5048 - ETA: 1s - loss: 8.1293 - acc: 0.4887 - ETA: 1s - loss: 8.0529 - acc: 0.4927 - ETA: 1s - loss: 8.2413 - acc: 0.4784 - ETA: 1s - loss: 8.0786 - acc: 0.4861 - ETA: 1s - loss: 8.0916 - acc: 0.4859 - ETA: 1s - loss: 8.2597 - acc: 0.4768 - ETA: 1s - loss: 8.2597 - acc: 0.4766 - ETA: 1s - loss: 8.2385 - acc: 0.4775 - ETA: 1s - loss: 8.2779 - acc: 0.4750 - ETA: 1s - loss: 8.2052 - acc: 0.4793 - ETA: 1s - loss: 8.2643 - acc: 0.4762 - ETA: 1s - loss: 8.2513 - acc: 0.4777 - ETA: 0s - loss: 8.1872 - acc: 0.4814 - ETA: 0s - loss: 8.1459 - acc: 0.4839 - ETA: 0s - loss: 8.1366 - acc: 0.4848 - ETA: 0s - loss: 8.1237 - acc: 0.4860 - ETA: 0s - loss: 8.1121 - acc: 0.4872 - ETA: 0s - loss: 8.0489 - acc: 0.4911 - ETA: 0s - loss: 8.1141 - acc: 0.4871 - ETA: 0s - loss: 8.1529 - acc: 0.4850 - ETA: 0s - loss: 8.1625 - acc: 0.4843 - ETA: 0s - loss: 8.1623 - acc: 0.4843 - ETA: 0s - loss: 8.1603 - acc: 0.4846 - ETA: 0s - loss: 8.1672 - acc: 0.4844 - ETA: 0s - loss: 8.1737 - acc: 0.4833 - ETA: 0s - loss: 8.1668 - acc: 0.4841 - ETA: 0s - loss: 8.1618 - acc: 0.4842 - ETA: 0s - loss: 8.1410 - acc: 0.4852 - ETA: 0s - loss: 8.1389 - acc: 0.4854 - ETA: 0s - loss: 8.1618 - acc: 0.4839 - ETA: 0s - loss: 8.1640 - acc: 0.4834 - ETA: 0s - loss: 8.1195 - acc: 0.4857Epoch 00013: val_loss improved from 8.66738 to 8.63480, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.1096 - acc: 0.4864 - val_loss: 8.6348 - val_acc: 0.4096
Epoch 15/20
6560/6680 [============================>.] - ETA: 2s - loss: 9.1316 - acc: 0.4000 - ETA: 1s - loss: 7.5681 - acc: 0.5200 - ETA: 1s - loss: 8.0615 - acc: 0.4925 - ETA: 1s - loss: 8.1864 - acc: 0.4817 - ETA: 1s - loss: 8.2000 - acc: 0.4813 - ETA: 1s - loss: 8.1913 - acc: 0.4820 - ETA: 1s - loss: 8.0742 - acc: 0.4892 - ETA: 1s - loss: 7.9716 - acc: 0.4957 - ETA: 1s - loss: 8.0229 - acc: 0.4938 - ETA: 1s - loss: 8.0476 - acc: 0.4911 - ETA: 1s - loss: 8.0024 - acc: 0.4940 - ETA: 1s - loss: 7.9546 - acc: 0.4968 - ETA: 1s - loss: 7.9833 - acc: 0.4950 - ETA: 1s - loss: 7.9631 - acc: 0.4962 - ETA: 1s - loss: 7.8964 - acc: 0.5004 - ETA: 0s - loss: 7.8719 - acc: 0.5013 - ETA: 0s - loss: 7.9820 - acc: 0.4950 - ETA: 0s - loss: 7.9929 - acc: 0.4947 - ETA: 0s - loss: 7.9739 - acc: 0.4963 - ETA: 0s - loss: 7.9625 - acc: 0.4971 - ETA: 0s - loss: 7.9631 - acc: 0.4970 - ETA: 0s - loss: 7.9877 - acc: 0.4954 - ETA: 0s - loss: 8.0403 - acc: 0.4922 - ETA: 0s - loss: 7.9863 - acc: 0.4956 - ETA: 0s - loss: 7.9634 - acc: 0.4962 - ETA: 0s - loss: 8.0176 - acc: 0.4924 - ETA: 0s - loss: 7.9976 - acc: 0.4940 - ETA: 0s - loss: 8.0358 - acc: 0.4920 - ETA: 0s - loss: 8.0267 - acc: 0.4923 - ETA: 0s - loss: 8.0362 - acc: 0.4920 - ETA: 0s - loss: 8.0539 - acc: 0.4911 - ETA: 0s - loss: 8.0805 - acc: 0.4895 - ETA: 0s - loss: 8.0550 - acc: 0.4909 - ETA: 0s - loss: 8.0857 - acc: 0.4890Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 8.0738 - acc: 0.4898 - val_loss: 8.6629 - val_acc: 0.3952
Epoch 16/20
6600/6680 [============================>.] - ETA: 1s - loss: 8.3137 - acc: 0.4500 - ETA: 1s - loss: 8.2256 - acc: 0.4792 - ETA: 1s - loss: 7.5989 - acc: 0.5130 - ETA: 1s - loss: 7.7419 - acc: 0.5076 - ETA: 1s - loss: 7.9933 - acc: 0.4930 - ETA: 1s - loss: 7.9303 - acc: 0.4981 - ETA: 1s - loss: 8.0331 - acc: 0.4903 - ETA: 1s - loss: 8.0520 - acc: 0.4889 - ETA: 1s - loss: 8.0811 - acc: 0.4866 - ETA: 1s - loss: 8.0338 - acc: 0.4880 - ETA: 1s - loss: 8.0444 - acc: 0.4877 - ETA: 1s - loss: 8.0058 - acc: 0.4902 - ETA: 1s - loss: 8.0179 - acc: 0.4889 - ETA: 1s - loss: 7.9856 - acc: 0.4913 - ETA: 0s - loss: 8.0174 - acc: 0.4898 - ETA: 0s - loss: 7.9850 - acc: 0.4911 - ETA: 0s - loss: 7.9823 - acc: 0.4914 - ETA: 0s - loss: 8.0198 - acc: 0.4895 - ETA: 0s - loss: 8.0333 - acc: 0.4890 - ETA: 0s - loss: 7.9930 - acc: 0.4919 - ETA: 0s - loss: 8.0008 - acc: 0.4913 - ETA: 0s - loss: 8.0089 - acc: 0.4903 - ETA: 0s - loss: 7.9788 - acc: 0.4926 - ETA: 0s - loss: 8.0066 - acc: 0.4914 - ETA: 0s - loss: 8.0024 - acc: 0.4921 - ETA: 0s - loss: 7.9912 - acc: 0.4928 - ETA: 0s - loss: 8.0017 - acc: 0.4923 - ETA: 0s - loss: 7.9908 - acc: 0.4930 - ETA: 0s - loss: 8.0109 - acc: 0.4920 - ETA: 0s - loss: 8.0234 - acc: 0.4909 - ETA: 0s - loss: 8.0074 - acc: 0.4922 - ETA: 0s - loss: 8.0100 - acc: 0.4916 - ETA: 0s - loss: 7.9932 - acc: 0.4927 - ETA: 0s - loss: 7.9643 - acc: 0.4944Epoch 00015: val_loss improved from 8.63480 to 8.52623, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.9789 - acc: 0.4933 - val_loss: 8.5262 - val_acc: 0.4144
Epoch 17/20
6500/6680 [============================>.] - ETA: 2s - loss: 9.1634 - acc: 0.4000 - ETA: 1s - loss: 7.7560 - acc: 0.5100 - ETA: 1s - loss: 7.8059 - acc: 0.5050 - ETA: 1s - loss: 7.9049 - acc: 0.4983 - ETA: 1s - loss: 7.9826 - acc: 0.4950 - ETA: 1s - loss: 8.0824 - acc: 0.4900 - ETA: 1s - loss: 8.1458 - acc: 0.4875 - ETA: 1s - loss: 8.1031 - acc: 0.4887 - ETA: 1s - loss: 8.1593 - acc: 0.4858 - ETA: 1s - loss: 7.9851 - acc: 0.4962 - ETA: 1s - loss: 8.0925 - acc: 0.4891 - ETA: 1s - loss: 8.0388 - acc: 0.4932 - ETA: 1s - loss: 7.9943 - acc: 0.4963 - ETA: 1s - loss: 7.9525 - acc: 0.4985 - ETA: 1s - loss: 7.9864 - acc: 0.4957 - ETA: 0s - loss: 8.0139 - acc: 0.4933 - ETA: 0s - loss: 8.0330 - acc: 0.4925 - ETA: 0s - loss: 8.0117 - acc: 0.4935 - ETA: 0s - loss: 8.0295 - acc: 0.4924 - ETA: 0s - loss: 8.0079 - acc: 0.4933 - ETA: 0s - loss: 8.0125 - acc: 0.4929 - ETA: 0s - loss: 8.0074 - acc: 0.4934 - ETA: 0s - loss: 7.9904 - acc: 0.4944 - ETA: 0s - loss: 7.9825 - acc: 0.4951 - ETA: 0s - loss: 7.9641 - acc: 0.4962 - ETA: 0s - loss: 7.9775 - acc: 0.4957 - ETA: 0s - loss: 7.9889 - acc: 0.4951 - ETA: 0s - loss: 7.9843 - acc: 0.4949 - ETA: 0s - loss: 7.9467 - acc: 0.4973 - ETA: 0s - loss: 7.9317 - acc: 0.4981 - ETA: 0s - loss: 7.9023 - acc: 0.4998 - ETA: 0s - loss: 7.9011 - acc: 0.4998 - ETA: 0s - loss: 7.8767 - acc: 0.5013 - ETA: 0s - loss: 7.8949 - acc: 0.5002Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.8934 - acc: 0.5001 - val_loss: 8.5263 - val_acc: 0.4084
Epoch 18/20
6620/6680 [============================>.] - ETA: 2s - loss: 5.8452 - acc: 0.6000 - ETA: 1s - loss: 7.6026 - acc: 0.5200 - ETA: 1s - loss: 7.7236 - acc: 0.5150 - ETA: 1s - loss: 7.6848 - acc: 0.5167 - ETA: 1s - loss: 7.7828 - acc: 0.5113 - ETA: 1s - loss: 7.6349 - acc: 0.5190 - ETA: 1s - loss: 7.6530 - acc: 0.5175 - ETA: 1s - loss: 7.6506 - acc: 0.5174 - ETA: 1s - loss: 7.6464 - acc: 0.5173 - ETA: 1s - loss: 7.6150 - acc: 0.5188 - ETA: 1s - loss: 7.5685 - acc: 0.5219 - ETA: 1s - loss: 7.6012 - acc: 0.5194 - ETA: 1s - loss: 7.5369 - acc: 0.5233 - ETA: 1s - loss: 7.5384 - acc: 0.5227 - ETA: 1s - loss: 7.5804 - acc: 0.5192 - ETA: 0s - loss: 7.5333 - acc: 0.5216 - ETA: 0s - loss: 7.5773 - acc: 0.5190 - ETA: 0s - loss: 7.6294 - acc: 0.5161 - ETA: 0s - loss: 7.6381 - acc: 0.5140 - ETA: 0s - loss: 7.6739 - acc: 0.5122 - ETA: 0s - loss: 7.7020 - acc: 0.5108 - ETA: 0s - loss: 7.7411 - acc: 0.5086 - ETA: 0s - loss: 7.7342 - acc: 0.5091 - ETA: 0s - loss: 7.7580 - acc: 0.5072 - ETA: 0s - loss: 7.7979 - acc: 0.5046 - ETA: 0s - loss: 7.8058 - acc: 0.5044 - ETA: 0s - loss: 7.8035 - acc: 0.5050 - ETA: 0s - loss: 7.8276 - acc: 0.5035 - ETA: 0s - loss: 7.8248 - acc: 0.5036 - ETA: 0s - loss: 7.8116 - acc: 0.5043 - ETA: 0s - loss: 7.8129 - acc: 0.5033 - ETA: 0s - loss: 7.8217 - acc: 0.5027 - ETA: 0s - loss: 7.8235 - acc: 0.5028 - ETA: 0s - loss: 7.7932 - acc: 0.5047Epoch 00017: val_loss improved from 8.52623 to 8.37625, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.7912 - acc: 0.5046 - val_loss: 8.3763 - val_acc: 0.4144
Epoch 19/20
6520/6680 [============================>.] - ETA: 2s - loss: 7.2550 - acc: 0.5500 - ETA: 1s - loss: 7.4736 - acc: 0.5364 - ETA: 1s - loss: 7.8144 - acc: 0.5095 - ETA: 1s - loss: 7.8983 - acc: 0.5032 - ETA: 1s - loss: 7.8633 - acc: 0.5049 - ETA: 1s - loss: 7.9085 - acc: 0.5020 - ETA: 1s - loss: 7.9021 - acc: 0.5016 - ETA: 1s - loss: 7.9721 - acc: 0.4972 - ETA: 1s - loss: 7.9337 - acc: 0.4988 - ETA: 1s - loss: 7.8806 - acc: 0.5016 - ETA: 1s - loss: 7.8459 - acc: 0.5034 - ETA: 1s - loss: 7.9251 - acc: 0.4987 - ETA: 1s - loss: 7.9614 - acc: 0.4967 - ETA: 1s - loss: 7.9637 - acc: 0.4969 - ETA: 1s - loss: 7.9551 - acc: 0.4975 - ETA: 0s - loss: 7.9547 - acc: 0.4973 - ETA: 0s - loss: 7.8780 - acc: 0.5019 - ETA: 0s - loss: 7.8456 - acc: 0.5030 - ETA: 0s - loss: 7.8091 - acc: 0.5056 - ETA: 0s - loss: 7.8026 - acc: 0.5064 - ETA: 0s - loss: 7.7974 - acc: 0.5061 - ETA: 0s - loss: 7.7798 - acc: 0.5072 - ETA: 0s - loss: 7.7703 - acc: 0.5078 - ETA: 0s - loss: 7.7418 - acc: 0.5088 - ETA: 0s - loss: 7.7496 - acc: 0.5084 - ETA: 0s - loss: 7.7495 - acc: 0.5087 - ETA: 0s - loss: 7.7586 - acc: 0.5086 - ETA: 0s - loss: 7.7713 - acc: 0.5081 - ETA: 0s - loss: 7.7791 - acc: 0.5078 - ETA: 0s - loss: 7.7783 - acc: 0.5070 - ETA: 0s - loss: 7.7343 - acc: 0.5098 - ETA: 0s - loss: 7.7416 - acc: 0.5093 - ETA: 0s - loss: 7.6946 - acc: 0.5119 - ETA: 0s - loss: 7.7084 - acc: 0.5113Epoch 00018: val_loss improved from 8.37625 to 8.31645, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.7059 - acc: 0.5114 - val_loss: 8.3164 - val_acc: 0.4204
Epoch 20/20
6600/6680 [============================>.] - ETA: 2s - loss: 8.8650 - acc: 0.4500 - ETA: 1s - loss: 7.6692 - acc: 0.5136 - ETA: 1s - loss: 7.4526 - acc: 0.5262 - ETA: 1s - loss: 7.4696 - acc: 0.5274 - ETA: 1s - loss: 7.6435 - acc: 0.5188 - ETA: 1s - loss: 7.6938 - acc: 0.5140 - ETA: 1s - loss: 7.6370 - acc: 0.5175 - ETA: 1s - loss: 7.5254 - acc: 0.5250 - ETA: 1s - loss: 7.4688 - acc: 0.5294 - ETA: 1s - loss: 7.5193 - acc: 0.5267 - ETA: 1s - loss: 7.6010 - acc: 0.5220 - ETA: 1s - loss: 7.6578 - acc: 0.5191 - ETA: 1s - loss: 7.6646 - acc: 0.5192 - ETA: 1s - loss: 7.6665 - acc: 0.5185 - ETA: 1s - loss: 7.7368 - acc: 0.5129 - ETA: 0s - loss: 7.7481 - acc: 0.5123 - ETA: 0s - loss: 7.7679 - acc: 0.5113 - ETA: 0s - loss: 7.7650 - acc: 0.5106 - ETA: 0s - loss: 7.7929 - acc: 0.5088 - ETA: 0s - loss: 7.8427 - acc: 0.5060 - ETA: 0s - loss: 7.8196 - acc: 0.5074 - ETA: 0s - loss: 7.8013 - acc: 0.5085 - ETA: 0s - loss: 7.7586 - acc: 0.5115 - ETA: 0s - loss: 7.7662 - acc: 0.5106 - ETA: 0s - loss: 7.7627 - acc: 0.5105 - ETA: 0s - loss: 7.7572 - acc: 0.5103 - ETA: 0s - loss: 7.7200 - acc: 0.5126 - ETA: 0s - loss: 7.7113 - acc: 0.5129 - ETA: 0s - loss: 7.7134 - acc: 0.5124 - ETA: 0s - loss: 7.7235 - acc: 0.5115 - ETA: 0s - loss: 7.7228 - acc: 0.5115 - ETA: 0s - loss: 7.6893 - acc: 0.5134 - ETA: 0s - loss: 7.6645 - acc: 0.5150 - ETA: 0s - loss: 7.6474 - acc: 0.5162Epoch 00019: val_loss improved from 8.31645 to 8.27664, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.6522 - acc: 0.5159 - val_loss: 8.2766 - val_acc: 0.4204
Wall time: 39.8 s

Load the Model with the Best Validation Loss

In [34]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [35]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 42.3445%

Predict Dog Breed with the Model

In [36]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [37]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
cmd = """bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
""".format(network="Xception")
exec(cmd)
# VGG19, Xception, Resnet50, InceptionV3
### TODO: Obtain bottleneck features from another pre-trained CNN.
cmd = """bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
""".format(network="VGG19")
exec(cmd)
### TODO: Obtain bottleneck features from another pre-trained CNN.
cmd = """bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
""".format(network="Resnet50")
exec(cmd)
### TODO: Obtain bottleneck features from another pre-trained CNN.
cmd = """bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
""".format(network="InceptionV3")
exec(cmd)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: I tried all 4 models and obtained the following results:

Model Test accuracy
VGG19 45.0957%
Resnet50 81.8182%
InceptionV3 80.1435%
Xception 84.0909%

Decided to go with Xception as it had the highest accuracy result. According to the author of this architecture Xception: Deep Learning with Depthwise Separable Convolutions, this architecture yields improved results over Inception V3, which itself was one of the top performers on the ImageNet dataset. As we are using transfer learning for this app, we take the bottleneck features, which are the output of our dog images processed through the Xception model before the fully connected layers, and add a GlobalAveragePooling2D layer to reduce them to a 2048 dimensional vector, which we pass to the Dense layer that we train to predict one of the 133 dog breeds we are interested in.

In [38]:
### TODO: Define your architecture.
Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dense(len(dog_names), activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 2048)              0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________
In [53]:
train_Xception.shape[1:]
Out[53]:
(7, 7, 2048)
### TODO: Define your architecture.
VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(len(dog_names), activation='softmax'))

VGG19_model.summary()
### TODO: Define your architecture.
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dense(len(dog_names), activation='softmax'))

Resnet50_model.summary()
### TODO: Define your architecture.
InceptionV3_model = Sequential()
InceptionV3_model.add(GlobalAveragePooling2D(input_shape=train_InceptionV3.shape[1:]))
InceptionV3_model.add(Dense(len(dog_names), activation='softmax'))

InceptionV3_model.summary()

(IMPLEMENTATION) Compile the Model

In [39]:
### TODO: Compile the model.
Xception_model.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"])
### TODO: Compile the model.
VGG19_model.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"])
### TODO: Compile the model.
Resnet50_model.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"])
### TODO: Compile the model.
InceptionV3_model.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [40]:
%%time
### TODO: Train the model.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets,
               validation_data=(valid_Xception, valid_targets),
               epochs=20, batch_size=20, callbacks=[checkpointer], verbose=2)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
Epoch 00000: val_loss improved from inf to 0.55385, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 1.0557 - acc: 0.7331 - val_loss: 0.5538 - val_acc: 0.8156
Epoch 2/20
Epoch 00001: val_loss improved from 0.55385 to 0.52579, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 0.3938 - acc: 0.8750 - val_loss: 0.5258 - val_acc: 0.8299
Epoch 3/20
Epoch 00002: val_loss improved from 0.52579 to 0.47535, saving model to saved_models/weights.best.Xception.hdf5
5s - loss: 0.3259 - acc: 0.8972 - val_loss: 0.4753 - val_acc: 0.8563
Epoch 4/20
Epoch 00003: val_loss did not improve
5s - loss: 0.2738 - acc: 0.9138 - val_loss: 0.5133 - val_acc: 0.8467
Epoch 5/20
Epoch 00004: val_loss did not improve
5s - loss: 0.2433 - acc: 0.9275 - val_loss: 0.5238 - val_acc: 0.8503
Epoch 6/20
Epoch 00005: val_loss did not improve
5s - loss: 0.2209 - acc: 0.9322 - val_loss: 0.4997 - val_acc: 0.8587
Epoch 7/20
Epoch 00006: val_loss did not improve
5s - loss: 0.1956 - acc: 0.9397 - val_loss: 0.5059 - val_acc: 0.8527
Epoch 8/20
Epoch 00007: val_loss did not improve
5s - loss: 0.1814 - acc: 0.9431 - val_loss: 0.5573 - val_acc: 0.8587
Epoch 9/20
Epoch 00008: val_loss did not improve
5s - loss: 0.1623 - acc: 0.9490 - val_loss: 0.5786 - val_acc: 0.8551
Epoch 10/20
Epoch 00009: val_loss did not improve
5s - loss: 0.1488 - acc: 0.9549 - val_loss: 0.5521 - val_acc: 0.8647
Epoch 11/20
Epoch 00010: val_loss did not improve
5s - loss: 0.1356 - acc: 0.9588 - val_loss: 0.5784 - val_acc: 0.8551
Epoch 12/20
Epoch 00011: val_loss did not improve
5s - loss: 0.1273 - acc: 0.9606 - val_loss: 0.6022 - val_acc: 0.8587
Epoch 13/20
Epoch 00012: val_loss did not improve
5s - loss: 0.1141 - acc: 0.9659 - val_loss: 0.6077 - val_acc: 0.8611
Epoch 14/20
Epoch 00013: val_loss did not improve
5s - loss: 0.1081 - acc: 0.9657 - val_loss: 0.6570 - val_acc: 0.8491
Epoch 15/20
Epoch 00014: val_loss did not improve
5s - loss: 0.0987 - acc: 0.9699 - val_loss: 0.6555 - val_acc: 0.8467
Epoch 16/20
Epoch 00015: val_loss did not improve
5s - loss: 0.0916 - acc: 0.9726 - val_loss: 0.6503 - val_acc: 0.8491
Epoch 17/20
Epoch 00016: val_loss did not improve
5s - loss: 0.0868 - acc: 0.9737 - val_loss: 0.6675 - val_acc: 0.8527
Epoch 18/20
Epoch 00017: val_loss did not improve
5s - loss: 0.0832 - acc: 0.9754 - val_loss: 0.6768 - val_acc: 0.8587
Epoch 19/20
Epoch 00018: val_loss did not improve
5s - loss: 0.0753 - acc: 0.9783 - val_loss: 0.6683 - val_acc: 0.8587
Epoch 20/20
Epoch 00019: val_loss did not improve
5s - loss: 0.0730 - acc: 0.9796 - val_loss: 0.6900 - val_acc: 0.8563
Wall time: 1min 45s
%%time
### TODO: Train the model.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', verbose=1, save_best_only=True)

VGG19_model.fit(train_VGG19, train_targets,
               validation_data=(valid_VGG19, valid_targets),
               epochs=20, batch_size=20, callbacks=[checkpointer], verbose=2)
%%time
### TODO: Train the model.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', verbose=1, save_best_only=True)

Resnet50_model.fit(train_Resnet50, train_targets,
               validation_data=(valid_Resnet50, valid_targets),
               epochs=20, batch_size=20, callbacks=[checkpointer], verbose=2)
%%time
### TODO: Train the model.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5', verbose=1, save_best_only=True)

InceptionV3_model.fit(train_InceptionV3, train_targets,
               validation_data=(valid_InceptionV3, valid_targets),
               epochs=20, batch_size=20, callbacks=[checkpointer], verbose=2)

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [41]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')
### TODO: Load the model weights with the best validation loss.
VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')
### TODO: Load the model weights with the best validation loss.
Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')
### TODO: Load the model weights with the best validation loss.
InceptionV3_model.load_weights('saved_models/weights.best.InceptionV3.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [42]:
### TODO: Calculate classification accuracy on the test dataset.
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

test_accuracy = 100 * np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: {:.4f}%'.format(test_accuracy))
Test accuracy: 83.6124%
### TODO: Calculate classification accuracy on the test dataset.
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]

test_accuracy = 100 * np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('Test accuracy: {:.4f}%'.format(test_accuracy))
# Test accuracy: 45.0957%
### TODO: Calculate classification accuracy on the test dataset.
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]

test_accuracy = 100 * np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy: {:.4f}%'.format(test_accuracy))
# Test accuracy: 81.8182%
### TODO: Calculate classification accuracy on the test dataset.
InceptionV3_predictions = [np.argmax(InceptionV3_model.predict(np.expand_dims(feature, axis=0))) for feature in test_InceptionV3]

test_accuracy = 100 * np.sum(np.array(InceptionV3_predictions)==np.argmax(test_targets, axis=1))/len(InceptionV3_predictions)
print('Test accuracy: {:.4f}%'.format(test_accuracy))
# Test accuracy: 80.1435%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [43]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

def Xception_predict_breed(img_path):
    # extract bottleneck features from Xception
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # get predicted vector
    predicted_vector = Xception_model.predict(bottleneck_feature)
    # return dog breed predicted by model
    return dog_names[np.argmax(predicted_vector)]
In [44]:
for i in range(20):
    img_path = test_files[i]
    predicted = Xception_predict_breed(img_path)
    actual = dog_names[np.argmax(test_targets[i])]
    print("{:2} [{:^7}] Predicted: {:25}  Actual: {:25}".format(i+1, "CORRECT" if predicted==actual else "WRONG", predicted, actual))
    
 1 [CORRECT] Predicted: Dalmatian                  Actual: Dalmatian                
 2 [CORRECT] Predicted: Doberman_pinscher          Actual: Doberman_pinscher        
 3 [CORRECT] Predicted: Papillon                   Actual: Papillon                 
 4 [CORRECT] Predicted: Bedlington_terrier         Actual: Bedlington_terrier       
 5 [CORRECT] Predicted: Flat-coated_retriever      Actual: Flat-coated_retriever    
 6 [ WRONG ] Predicted: Giant_schnauzer            Actual: Belgian_sheepdog         
 7 [CORRECT] Predicted: Canaan_dog                 Actual: Canaan_dog               
 8 [CORRECT] Predicted: Clumber_spaniel            Actual: Clumber_spaniel          
 9 [CORRECT] Predicted: Lakeland_terrier           Actual: Lakeland_terrier         
10 [CORRECT] Predicted: Chow_chow                  Actual: Chow_chow                
11 [CORRECT] Predicted: Afghan_hound               Actual: Afghan_hound             
12 [CORRECT] Predicted: Bedlington_terrier         Actual: Bedlington_terrier       
13 [CORRECT] Predicted: Glen_of_imaal_terrier      Actual: Glen_of_imaal_terrier    
14 [CORRECT] Predicted: Yorkshire_terrier          Actual: Yorkshire_terrier        
15 [CORRECT] Predicted: German_shepherd_dog        Actual: German_shepherd_dog      
16 [ WRONG ] Predicted: Bull_terrier               Actual: Basenji                  
17 [CORRECT] Predicted: Pomeranian                 Actual: Pomeranian               
18 [CORRECT] Predicted: Boston_terrier             Actual: Boston_terrier           
19 [CORRECT] Predicted: Japanese_chin              Actual: Japanese_chin            
20 [CORRECT] Predicted: Cairn_terrier              Actual: Cairn_terrier            

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [45]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
from matplotlib.patches import Circle

def get_dog_image(breed=None, root='dogImages/test'):
    """Get a sample image of a specified dog breed to show in the app"""
    folders = glob(root + '/*')
    breed_label = breed.replace(" ", "_")
    breed_folder = [folder for folder in folders if breed_label in folder]
    if breed_folder:
        files = glob(breed_folder[0] + "/*")
        return random.choice(files)

def crop_img_square(img):
    """Crops rgb image to a square"""
    h, w = img.shape[0], img.shape[1]
    min_dim = min(h, w)
    start_h = h//2 - min_dim//2
    start_w = w//2 - min_dim//2
    #print(start_h, start_w)
    return img[start_h:start_h+min_dim, start_w:start_w+min_dim, :]
    
def show_image(img_path, inset_img_path=None, title_text='Title', subtitle_text=None, inset_text=None):
    """Displays an image, with optional title text and secondary inset image"""
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    imgplot = plt.imshow(cv_rgb)
    plt.axis('off')
    img_extent = imgplot.get_extent()
    #print(img_extent)
    bbox_props = dict(boxstyle="round4,pad=0.3", fc="#FFF2F2", ec="#D18E53", lw=2)
    font = {'family': 'monospace', 'color':  '#6B8A99', 'weight': 'normal', 'size': 16}
    plt.text(img_extent[1]/2,-20, title_text, bbox=bbox_props, fontdict=font, horizontalalignment='center')
    if subtitle_text:
        plt.text(img_extent[1]/2, 1.2*img_extent[2], subtitle_text, bbox=bbox_props, fontdict=font, horizontalalignment='center')

    if inset_img_path:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        inset_img = cv2.imread(inset_img_path)
        #print(inset_img.shape)
        inset_img = crop_img_square(inset_img) # crop to a square
        #print(inset_img.shape)
        inset_cv_rgb = cv2.cvtColor(inset_img, cv2.COLOR_BGR2RGB)
        ax_img = ax.imshow(inset_cv_rgb)
        ax_img_extent = ax_img.get_extent()
        #print(ax_img_extent)
        min_ax_img_dim = min(ax_img_extent[1], ax_img_extent[2])
        circle = Circle((ax_img_extent[1]/2, ax_img_extent[2]/2), min_ax_img_dim/2.1, facecolor='none',
                    edgecolor="#F73D3D", linewidth=8, alpha=0.5)
        ax.add_patch(circle)
        ax_img.set_clip_path(circle)
        if inset_text:
            plt.text(ax_img_extent[1]/2, ax_img_extent[2], inset_text, bbox=bbox_props, fontdict=font, horizontalalignment='center')
        ax.axis('off')
    plt.tight_layout()
    plt.show()
In [46]:
def dog_breed_analyser(img_path):
    """Analyses a photo and determines if photo is of a human or dog, and identifies the closest matching breed"""
    title_text, subtitle_text, inset_text, inset_img_path = "", "", "", ""
    if dog_detector(img_path):
        # dog detected
        print("Dog detected")
        breed = Xception_predict_breed(img_path).replace("_", " ")
        title_text = "This is a lovely photo of a"
        subtitle_text = breed
    elif face_detector(img_path):
        # human detected
        print("Human detected")
        breed = Xception_predict_breed(img_path).replace("_", " ")
        title_text = "You are most probably human."
        subtitle_text = "But you were a dog,\nyou'll be mistaken for a"
        inset_text = breed
        inset_img_path = get_dog_image(breed)
    else:
        # neither dog or human detected
        print("Unknown input detected")
        title_text = "Beep boop boop. :("
        subtitle_text = "We are 99% sure \nthere are no \nhumans or dogs \ndetected in this image!"
    show_image(img_path, inset_img_path=inset_img_path, title_text=title_text, subtitle_text=subtitle_text, inset_text=inset_text)

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: The output for dogs got 2 out of 8 wrong, which is in line with the earlier Xception_predictions test accuracy of 83%. It mistook the Australian Terrier for a Norwich Terrier, which honestly looks similar. It also mistook the brown Labrador Retriever for a German Shorthair Pointer, which also comes in brown with similar shaped ears and faces. The output for humans is a little worse than expected, with the exception for the Irish Water Spaniel looking like the human with the poofy hair, the rest of the matches have little resemblance to the human faces. There were also quite a number of repeated breeds, like the Lowchen and Petit basset griffon vendeen.

The algorithm could be improved by:

  1. Providing the top 3 resembling breeds and their percentages for each human face, eg "You are a mix of 60% Labrador, 25% Poodle and 15% Silky terrier" for possibly more entertainment value.
  2. Detecting bounding box for human faces in group photos and cropping to each face to predict resembling dog breed for each separate face in the group photo.
  3. Providing parentage breeds for mixed breed dogs.
In [47]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
dog_breed_analyser('images/Welsh_springer_spaniel_08203.jpg')
Dog detected
In [48]:
dog_breed_analyser('images/sample_human_output.png')
Human detected
In [49]:
for file in glob('test_app/humans/*'):
    dog_breed_analyser(file)
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Human detected
Unknown input detected
Human detected
Human detected
In [50]:
for file in glob('test_app/dogs/*'):
    dog_breed_analyser(file)
Dog detected
Dog detected
Dog detected
Dog detected
Dog detected
Dog detected
Dog detected